import { App, Input, Modal, Popover, Skeleton } from 'antd'
import cs from 'classnames'
import Image from 'next/image'
import { useEffect, useRef, useState } from 'react'

import { Violation } from '@/api/interface'
import { ReplyRes } from '@/api/interface/entity'
import { UploadFile } from '@/api/modules/entity'
import { Reply, ReplyList } from '@/api/modules/entity'
import alert from '@/assets/images/alert-circle.png'
import close from '@/assets/images/close.png'
import file from '@/assets/images/file.png'
import repliedAvatar from '@/assets/images/replied-logo.png'
import useLocale from '@/utils/useLocale'

import locale from './locale'
import Replied from './Replied'
import styles from './styles/unReply.module.less'

const { TextArea } = Input

const fileTypes = [
  'image/pjpeg',
  'image/jpeg',
  'image/png',
  'application/msword',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  'application/vnd.ms-excel',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  'application/pdf',
]

function UnReply({
  violation,
  isModalOpen,
  setIsModalOpen,
  refresh,
}: {
  violation: Partial<Violation>
  isModalOpen: boolean
  setIsModalOpen: (_: boolean) => void
  refresh: () => void
}) {
  const t = useLocale(locale)

  const { message } = App.useApp()

  const [repliedModal, setRepliedModal] = useState(false)

  const [fileList, setFileList] = useState<string[]>([])

  const FileUploadComponent = () => {
    const fileInputRef = useRef<HTMLInputElement | null>(null)
    const handleFileSelect = () => {
      if (fileInputRef.current) {
        fileInputRef.current.value = ''
        fileInputRef.current.click()
      }
    }

    const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
      const files = e.target.files
      if (files?.length! > 5) return message.warning(t['reply.attachments.upload.length.warning'])
      if (files) {
        const uploadPromises = Array.from(files).map(async (file) => {
          const imgType = fileTypes.includes(file.type)
          const imgSize = file.size / 1024 / 1024 < 200
          if (!imgType) {
            message.warning(t['reply.attachments.upload.type.warning'])
            return null
          }
          if (!imgSize) {
            message.warning(t['reply.attachments.upload.size.warning'])
            return null
          }

          const excelFormData = new FormData()
          excelFormData.append('file', file)
          const { data } = await UploadFile(excelFormData)
          return data
        })

        const uploadedFiles = await Promise.all(uploadPromises)

        // Filter out null values (warnings) and update the state with uploaded files
        const filteredFiles = uploadedFiles.filter((file) => file !== null) as string[]

        setFileList([...fileList, ...filteredFiles])
      }
    }

    const delFile = (file: string) => {
      setFileList(fileList?.filter((item) => item !== file))
    }

    return (
      <>
        {fileList.length ? (
          <div className={styles['un-replied-attachments-file']}>
            {fileList.map((item) => {
              return (
                <div className={styles['un-replied-attachments-file-item']} key={item}>
                  <Image src={file} className={styles['file-icon']} alt="file" />
                  <span className={styles['file-text']}>{item}</span>
                  <Image
                    onClick={() => delFile(item)}
                    src={close}
                    className={styles['file-close']}
                    alt="close"
                  />
                </div>
              )
            })}
          </div>
        ) : (
          <></>
        )}

        <div className={styles['un-replied-attachments-add']}>
          <span onClick={handleFileSelect}>{t['reply.attachments.add']}</span>
          <input
            type="file"
            multiple
            style={{ display: 'none' }}
            ref={fileInputRef}
            onChange={handleFileUpload}
            accept=".jpeg,.png,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.pdf"
          />
        </div>
      </>
    )
  }

  useEffect(() => {
    isModalOpen && getRepliedList()
    setFileList([])
  }, [isModalOpen])

  const [loading, setLoading] = useState(true)
  const [replied, setReplied] = useState<ReplyRes[]>([])
  const getRepliedList = async () => {
    try {
      setLoading(true)
      const { data } = await ReplyList({ refNumber: violation.refNumber! })
      const unReplied = data.filter((item) => item.status === 0 && item.source === 'INT')
      setReplied(unReplied)
      unReplied.length && setRepliedActive(unReplied[0])
    } finally {
      setLoading(false)
    }
  }

  const [repliedActive, setRepliedActive] = useState<Partial<ReplyRes>>({})
  const clickReplied = (item: ReplyRes) => {
    if (item.id === repliedActive.id) return
    setFileList([])
    setRepliedActive(item)
  }

  const handleCancel = () => {
    setIsModalOpen(false)
  }

  const [content, setContent] = useState('')

  const handleSubmit = async () => {
    if (!content || content.length < 5) return message.warning(t['reply.content.error'])
    const params = {
      attachment: fileList,
      content: content,
      refNumber: violation.refNumber!,
      replyTo: repliedActive.id!,
    }
    await Reply(params)
    message.success(t['reply.content.success'])
    setIsModalOpen(false)
    refresh()
  }

  return (
    <Modal
      centered
      width={900}
      title={violation.refNumber}
      footer={false}
      open={isModalOpen}
      onCancel={handleCancel}
      className={styles['un-replied-modal']}
      classNames={{
        header: styles['un-replied-header'],
        body: styles['un-replied-body'],
      }}
      wrapClassName={styles['un-replied-wrapper']}
    >
      <Skeleton
        loading={loading}
        title={false}
        active
        paragraph={{ rows: 15 }}
        style={{ padding: '20px' }}
      >
        <div className={styles['un-replied']}>
          <div className={styles['un-replied-left']}>
            <div className={styles['un-replied-left-title']}>
              <span className={styles['un-replied-title-text']}>{t['reply.title.unReply']}</span>
              <span className={styles['un-replied-title-num']}>{violation.unRepliedCount}</span>
            </div>
            <div className={styles['un-replied-left-list']}>
              {replied.map((item) => {
                return (
                  <div
                    className={cs(
                      styles['un-replied-item'],
                      item.id === repliedActive.id && styles['un-replied-item-active']
                    )}
                    key={item.id}
                    onClick={() => clickReplied(item)}
                  >
                    <div className={styles['un-replied-item-main']}>
                      <Image
                        src={repliedAvatar}
                        className={styles['un-replied-item-avatar']}
                        alt="replied-avatar"
                      />
                      <div className={styles['un-replied-item-content']}>
                        <div className={styles['un-replied-item-title']}>
                          <span className={styles['un-replied-item-name']}>{item.createdBy}</span>
                          <span className={styles['un-replied-item-date']}>{item.createdAt}</span>
                        </div>
                        <span className={styles['un-replied-item-description']}>
                          {item.content ? item.content : '--'}
                        </span>
                      </div>
                    </div>
                  </div>
                )
              })}
            </div>
            <div className={styles['un-replied-left-footer']}>
              <div className={styles['un-replied-button']} onClick={() => setRepliedModal(true)}>
                <span className={styles['un-replied-button-text']}>{t['reply.title.replied']}</span>
              </div>
            </div>
          </div>

          <div className={styles['un-replied-right']}>
            <div className={styles['un-replied-right-title']}>
              <div className={styles['un-replied-title-logo']}>
                <Image
                  src={repliedAvatar}
                  className={styles['un-replied-title-avatar']}
                  alt="replied-avatar"
                />
                <span className={styles['un-replied-title-name']}>{repliedActive.createdBy}</span>
              </div>
              <span className={styles['un-replied-title-date']}>{repliedActive.createdAt}</span>
            </div>
            <div className={styles['un-replied-detail']}>
              <span className={styles['un-replied-detail-start']}>
                <span>‘</span>
                <span>‘</span>
              </span>
              <span className={styles['un-replied-detail-text']}>
                {repliedActive.content ? repliedActive.content : '--'}
              </span>
              <span className={styles['un-replied-detail-end']}>
                <span>’</span>
                <span>’</span>
              </span>
            </div>
            <div className={styles['un-replied-textarea']}>
              <span className={styles['un-replied-textarea-label']}>{t['reply.title']}</span>
              <TextArea
                rows={6}
                placeholder={t['reply.content.placeholder']}
                showCount
                maxLength={1000}
                onChange={(e) => setContent(e.target.value)}
              />
            </div>
            <div className={styles['un-replied-attachments']}>
              <span className={styles['un-replied-attachments-label']}>
                {t['reply.attachments']}
                <Popover placement="right" content={t['reply.attachments.upload.type']}>
                  <Image
                    src={alert}
                    alt="alert"
                    className={styles['un-replied-alert-icon']}
                  ></Image>
                </Popover>
              </span>
              <FileUploadComponent />
            </div>
            <div className={styles['un-replied-right-footer']}>
              <div className={styles['un-replied-submit']} onClick={() => handleSubmit()}>
                <span className={styles['un-replied-submit-text']}>{t['reply.submit']}</span>
              </div>
            </div>
          </div>
        </div>
      </Skeleton>

      <Replied isModalOpen={repliedModal} setIsModalOpen={setRepliedModal} violation={violation} />
    </Modal>
  )
}
export default UnReply
